package com.onec.service.design.cglib;

import com.onec.service.design.proxy.OrderServiceImpl;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;


/**
 * cglib 动态代理
 */

public class DynamicLogCglibProxy implements MethodInterceptor {

  private static final Logger LOGGER = LoggerFactory.getLogger(DynamicLogCglibProxy.class);

  private Enhancer enhancer = new Enhancer();

  public Object getProxyObj(Class clazz) {
    enhancer.setSuperclass(clazz);
    enhancer.setCallback(this);
    enhancer.setUseCache(false);
    return enhancer;
  }


  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    LOGGER.info("日志开始");
    Object object = methodProxy.invokeSuper(o, objects);
    LOGGER.info("日志结束：");
    return object;
  }
}

//测试示例
class Test {

  public static void main(String[] args) {

    DynamicLogCglibProxy dynamicLogCglibProxy = new DynamicLogCglibProxy();
    OrderServiceImpl orderService = (OrderServiceImpl) dynamicLogCglibProxy.getProxyObj(OrderServiceImpl.class);
    orderService.createOrder();
  }
}
